package com.server.util;


import cn.hutool.core.util.StrUtil;
import com.server.component.RedisUtil;
import com.server.constant.RedisKey;
import com.server.exception.AccessTokenException;
import com.server.vo.upms.user.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 基础控制器
 * </p>
 *
 * @author gdj
 * @since 2019-08-16
 */
@Slf4j
@ControllerAdvice
public class BaseController {

    @Autowired
    private RedisUtil redisUtil;

    public HttpServletRequest getRequest() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
        return request;
    }

    /**
     * 根据token获取用户
     * @return
     */
    public UserInfo getUser(){
        String _token = this.getRequest().getHeader("_token");
        if (StrUtil.isBlank(_token)) {
            throw new AccessTokenException("认证失败,请重新登录");
        } else {
            UserInfo userInfo= (UserInfo) redisUtil.get(RedisKey.ADMIN_USER+":"+_token);
            if(userInfo==null){
                throw new AccessTokenException("认证失败,请重新登录");
            }else {
                return userInfo;
            }
        }
    }
}
